package com.soc.auth.security;

import com.soc.auth.enumes.ResponseStatusEnum;
import com.soc.auth.utils.ResponseUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 认证失败后调用该方法
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {

        String exceptionMessage = exception.getMessage();

        if (exception instanceof BadCredentialsException) {
            exceptionMessage = "密码错误";
        }

        ResponseUtil.response(response, ResponseStatusEnum.AuthError.getCode(), ResponseStatusEnum.AuthError.getMessage(), exceptionMessage);
    }
}
